package jgl.vajra.kingkong.part.home.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import jgl.vajra.kingkong.R;
import jgl.vajra.kingkong.bean.AddressBean;
import jgl.vajra.kingkong.bean.CityChoiceBean;
import jgl.vajra.kingkong.bean.HomeCarModelBean;
import jgl.vajra.kingkong.bean.HomeMechanicsBean;
import jgl.vajra.kingkong.bean.HomePlaceBean;
import jgl.vajra.kingkong.bean.MarketPriceBean;
import jgl.vajra.kingkong.bean.OpenCityBean;
import jgl.vajra.kingkong.bean.OrderParametersBean;
import jgl.vajra.kingkong.bean.ReservedCarTimeBean;
import jgl.vajra.kingkong.bean.SpeechInfoBean;
import jgl.vajra.kingkong.databinding.FragmentHomePageBinding;
import jgl.vajra.kingkong.dialogFragment.OrderNotCompletedDialogFragment;
import jgl.vajra.kingkong.dialogFragment.ShareFriendsDialogFragment;
import jgl.vajra.kingkong.event.CityChoiceEvent;
import jgl.vajra.kingkong.event.GrabOrderLoginStateEvent;
import jgl.vajra.kingkong.event.WorkplaceEvent;
import jgl.vajra.kingkong.manager.AccountManager;
import jgl.vajra.kingkong.manager.FragmentManager;
import jgl.vajra.kingkong.manager.IntentManager;
import jgl.vajra.kingkong.manager.UMShareManager;
import jgl.vajra.kingkong.netty.ClientHandler;
import jgl.vajra.kingkong.netty.ImConnection;
import jgl.vajra.kingkong.part.home.contract.HomePageContract;
import jgl.vajra.kingkong.part.home.pop.AccountingMethodPop;
import jgl.vajra.kingkong.part.home.pop.AllCarTypePop;
import jgl.vajra.kingkong.part.home.pop.AllMachineryPop;
import jgl.vajra.kingkong.part.home.pop.OwnBidPop;
import jgl.vajra.kingkong.part.home.viewModel.HomePageViewModel;
import jgl.vajra.kingkong.utils.RandomUtils;
import jgl.vajra.kingkong.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.kingkong.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.kingkong.widget.manager.LoadingFragmentManager;
import jgl.vajra.kingkong.widget.manager.SPManager;
import jgl.vajra.kingkong.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.kingkong.widget.mvvm.view.BaseMVVMFragment;
import jgl.vajra.kingkong.widget.retrofithelper.rxsubscriber.CommonObserver;
import jgl.vajra.kingkong.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.kingkong.widget.utils.ToastUtils;
import jgl.vajra.kingkong.widget.utils.UIUtils;
import jgl.vajra.kingkong.widget.view.tablayout.TabLayout;

@CreateViewModel(HomePageViewModel.class)
public class HomePageFragment extends BaseMVVMFragment<HomePageViewModel, FragmentHomePageBinding> implements HomePageContract.View, BaseBindingItemPresenter {

    //浮动按钮按下时x坐标
    private float downX;
    //浮动按钮按下时y坐标
    private float downY;
    /**
     * 按下时浮层x坐标
     */
    float downViewX = 0;

    private SingleTypeBindingAdapter adapterMechanics;
    private SingleTypeBindingAdapter adapterPlace;
    private List<HomeMechanicsBean> listMechanics = new ArrayList<>();
    private List<HomePlaceBean> listPlace = new ArrayList<>();
    private AllMachineryPop allMachineryPop;
    private AccountingMethodPop accountingMethodPop;
    private boolean isCityPicker = false;
    private boolean isSettleAccounts = false;
    private OrderNotCompletedDialogFragment orderNotCompletedDialogFragment;
    private OwnBidPop ownBidPop;
    private AllCarTypePop allCarTypePop;
    private List<HomeCarModelBean> carModelBean;
    private int settleAccountsId;
    private String settleAccountsContent;
    private String area;
    private AddressBean addressData;

    private int priceType = 0;//出价类型
    private SpeechInfoBean speechInfoBean;
    private OptionsPickerView<String> pvOptions;
    private MarketPriceBean marketPriceBean;
    private List<CityChoiceBean> cityChoiceBean;
    private OpenCityBean openCityBean;

    public boolean startDischarge = false;
    public boolean placeDischarge = false;

    //上传的地址
    private List<OrderParametersBean.AddressData> addressDataBean = new ArrayList<>();
    private List<OrderParametersBean.AddressData> singleAddressData = new ArrayList<>();
    private List<OrderParametersBean.AddressData> multipleAddressData = new ArrayList<>();
    private List<OrderParametersBean.AddressData> multipleAddressOne = new ArrayList<>();
    private List<OrderParametersBean.AddressData> multipleAddressTwo = new ArrayList<>();
    private Boolean isSingleAndMultiple=false;//true 多个地址,false 单个地址
    private String typeModel;
    private ShareFriendsDialogFragment shareFriendsDialogFragment;
    private CityChoiceBean selectLocationData;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home_page;
    }

    @Override
    public void initView() {
        mBinding.setView(this);


        mBinding.tvTip.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        mBinding.tvTip.setSelected(true);
        mBinding.tvTip.setFocusable(true);
        mBinding.tvTip.setFocusableInTouchMode(true);

        mBinding.tvTitle.setText(16, 0, UIUtils.getColor(R.color.color_0f2cbb));//设置属性
        mBinding.tvTitle.setTextStillTime(3000);//设置停留时长间隔
        mBinding.tvTitle.setAnimTime(300);//设置进入和退出的时间间隔
        mBinding.tvTitle.setOnItemClickListener(position -> Logger.d(position + "点击了"));

        //位置信息
        addressData = SPManager.HomeData.getAddressData();

        //上一次选择的
        selectLocationData = SPManager.HomeData.getSelectLocationData();
        if (selectLocationData != null && !TextUtils.isEmpty(selectLocationData.abbreviation)) {
            area= selectLocationData.areaCode;
            mBinding.tvAddress.setText(selectLocationData.abbreviation);
        }

        requestNetData();

        //机械类型
        // 不可嵌套滑动
        mBinding.recyclerViewMechanics.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerViewMechanics.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerViewMechanics.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        adapterMechanics = new SingleTypeBindingAdapter(mActivity, listMechanics, R.layout.item_home_page_mechanics);
        mBinding.recyclerViewMechanics.setAdapter(adapterMechanics);
        adapterMechanics.setItemPresenter(this);


        //新增地址
        // 不可嵌套滑动
        mBinding.recyclerViewPlace.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerViewPlace.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerViewPlace.setLayoutManager(new LinearLayoutManager(getContext()));
        adapterPlace = new SingleTypeBindingAdapter(mActivity, listPlace, R.layout.item_home_page_place);
        mBinding.recyclerViewPlace.setAdapter(adapterPlace);
        adapterPlace.setItemPresenter(this);

        mBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                resetData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        ImConnection.getInstance().connect();//连接
        Observable.interval(30, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new CommonObserver() {
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                //是否在线
                Logger.d("是否在线" + ClientHandler.isLogin);
                if (ClientHandler.isLogin) {

                    mBinding.ivState.setImageResource(R.drawable.ic_line_on);
                    mBinding.tvStateText.setText("在线");
                    mBinding.tvReconnect.setVisibility(View.GONE);

                    long currentTime = System.currentTimeMillis();
                    long heartbeatLastTime = SPManager.HomeData.getSocketHeartbeatLastTime() + 200000;
                    if (currentTime > heartbeatLastTime) {
                        ClientHandler.isLogin = false;
                        mBinding.ivState.setImageResource(R.drawable.ic_line_off);
                        mBinding.tvStateText.setText("离线");
                        mBinding.tvReconnect.setVisibility(View.VISIBLE);
                        ImConnection.getInstance().connect();//连接
                    }

                    Logger.d(currentTime + "是否在线啊" + heartbeatLastTime);

                } else {
                    mBinding.ivState.setImageResource(R.drawable.ic_line_off);
                    mBinding.tvStateText.setText("离线");
                    mBinding.tvReconnect.setVisibility(View.VISIBLE);
                    ImConnection.getInstance().connect();//连接
                    Logger.d("连接中");
                }
                mBinding.llState.setVisibility(View.VISIBLE);
            }
        });

        //获取屏幕宽度
        WindowManager wm = (WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        final int with = outMetrics.widthPixels;
        final int height = outMetrics.heightPixels;
        mBinding.ivShareFriends.setOnTouchListener((v, event) -> {
            //返回false，是点击事件；返回true，不记为点击事件 参考链接  https://blog.csdn.net/u014043113/article/details/74778414
            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    //按下
                    downX = event.getX();
                    downY = event.getY();
                    downViewX = mBinding.ivShareFriends.getX();
                    return true;
                case MotionEvent.ACTION_MOVE:
                    //移动
                    //移动的距离
                    float moveX = event.getX() - downX;// event.getX() 移动的X距离
                    float moveY = event.getY() - downY;// event.getY() 移动的Y距离
                    //当前view= X,Y坐标
                    float viewX = mBinding.ivShareFriends.getX();
                    float viewY = mBinding.ivShareFriends.getY();
                    //view的宽高
                    int viewHeigth = mBinding.ivShareFriends.getWidth();
                    int viewWidth = mBinding.ivShareFriends.getHeight();

                    //X当超出屏幕,取最大值
                    if (viewX + moveX + viewWidth > with) {
                        //靠右
                        mBinding.ivShareFriends.setX(with - viewWidth);
                    } else if (viewX + moveX <= 0) {
                        //靠右
                        mBinding.ivShareFriends.setX(0);
                    } else {
                        //正常
                        mBinding.ivShareFriends.setX(viewX + moveX);
                    }
                    //Y当超出屏幕,取最大值
                    if (viewY + moveY + viewHeigth > height) {
                        //靠下
                        mBinding.ivShareFriends.setY(height - viewHeigth);
                    } else if (viewY + moveY <= 0) {
                        //靠上
                        mBinding.ivShareFriends.setY(0);
                    } else {
                        //正常
                        mBinding.ivShareFriends.setY(viewY + moveY);
                    }
                    return true;


                case MotionEvent.ACTION_UP:
                    //松手
                    float upX = mBinding.ivShareFriends.getX();
                    //屏幕中心点
                    float center = with / 2;
                    if (mBinding.ivShareFriends.getX() > center) {
                        //靠右
                        mBinding.ivShareFriends.setX(with - mBinding.ivShareFriends.getWidth());
                    } else {
                        mBinding.ivShareFriends.setX(0);
                    }
                    //按下时与松手时X值一致的话，就干点别的事情
                    if (downViewX == upX) {
                        if (shareFriendsDialogFragment == null)
                            shareFriendsDialogFragment = new ShareFriendsDialogFragment();
                        shareFriendsDialogFragment.setShareData(mActivity);
                        shareFriendsDialogFragment.show(mActivity.getSupportFragmentManager());
                        return false;
                    } else {
                        return true;
                    }
            }

            return false;
        });
    }

    public void requestNetData() {

        //获取位置开放城市
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));//随机数

        mViewModel.getCarTypeData(map);

        //mViewModel.getAreaInfoData(map);
        mViewModel.getOpenCityData(map);

        Map<String, Object> mapSpeech = new HashMap<>();
        mapSpeech.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));//随机数
        mapSpeech.put("type", 1);
        //头部轮播提示语
        mViewModel.getSpeechInfoData(mapSpeech);
    }

    public void getCarModelData(String type) {
        typeModel = type;
        //机械型号
        Map<String, Object> mapCarModel = new HashMap<>();
        mapCarModel.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));
        mapCarModel.put("type", type);
        mViewModel.getCarModelData(mapCarModel);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }


    @Override
    public void onItemClick(int position, Object itemData) {

    }

    //位置
    @Override
    public void onTriangle() {
        IntentManager.toCityChoiceActivity(mActivity);
    }

    //礼盒
    @Override
    public void onGiftBox() {
        //订单
        //   IntentManager.toOrderStatusActivity(mActivity);

//        IntentManager.toOrderEvaluateActivity(mActivity);

//        IntentManager.toOwnerDetailsActivity(mActivity, "4434763375");
    }

    //重新连接
    @Override
    public void onReconnect() {
        if (!ClientHandler.isLogin) {
            //ToastUtils.showShort("重新连接中");
            LoadingFragmentManager.getInstance().showLoadingDialog(null, "连接中");
            ImConnection.getInstance().connect();//连接
        }
    }

    //全部机械
    @Override
    public void onAllMachinery() {
        if (allMachineryPop == null)
            allMachineryPop = new AllMachineryPop(mActivity, listMechanics);
        allMachineryPop.setAllMachineryListener((position, itemData) -> {
            if (listMechanics.get(position).isClick) {
                return;
            }
            for (int i = 0; i < listMechanics.size(); i++) {
                listMechanics.get(i).isClick = false;
            }

            listMechanics.get(position).isClick = true;
            adapterMechanics.refresh();

            mBinding.tabLayout.getTabLayout().removeAllTabs();
            setLocationType(itemData.multipleAddresses);
            getCarModelData(itemData.type);
        });
        allMachineryPop.showPopupWindow(mBinding.rlHead);
    }

    //全部车型
    @Override
    public void onAllVehicle() {
        allCarTypePop = new AllCarTypePop(mActivity, carModelBean);
        allCarTypePop.showPopupWindow(mBinding.tvAllMachinery);
        allCarTypePop.setAllCarTypeListener((position, itemData) -> {
            mBinding.tabLayout.setCurrentItem(position);
        });
    }

    //台班算账
    @Override
    public void onShiftAccounting() {
        mBinding.tvMileageAccounting.setBackgroundResource(R.drawable.shape_color_c4c8de_10dp_right);
        mBinding.tvShiftAccounting.setBackgroundResource(R.drawable.shape_while_10dp_top_left);
        mBinding.ivAccountingBg.setImageResource(R.drawable.ic_shift_accounting);
        mBinding.tvMileageAccounting.setTextColor(UIUtils.getColor(R.color.white));
        mBinding.tvShiftAccounting.setTextColor(UIUtils.getColor(R.color.color_333333));

        mBinding.etAccounting.setHint("选择干活时长(台班)");
    }

    //里程算账
    @Override
    public void onMileageAccounting() {
        mBinding.ivAccountingBg.setImageResource(R.drawable.ic_mileage_accounting);
        mBinding.tvMileageAccounting.setBackgroundResource(R.drawable.shape_while_10dp_top_right);
        mBinding.tvShiftAccounting.setBackgroundResource(R.drawable.shape_color_c4c8de_10dp_left);
        mBinding.tvShiftAccounting.setTextColor(UIUtils.getColor(R.color.white));
        mBinding.tvMileageAccounting.setTextColor(UIUtils.getColor(R.color.color_333333));

        mBinding.etAccounting.setHint("选择里程算账(一趟)");
    }

    public void resetData() {
        settleAccountsId = 0;
        settleAccountsContent = "";
        mBinding.tvSettleAccounts.setText("选择算账方式");
        isSettleAccounts = false;
        mBinding.llBudget.setVisibility(View.GONE);
        mBinding.llBottom.setBackgroundResource(0);
        mBinding.llOwnBid.setVisibility(View.GONE);
        mBinding.tvOwnBidPrice.setText("");
        mBinding.tvWnBid.setVisibility(View.VISIBLE);
        priceType = 0;
        mBinding.ivMarketPrice.setImageResource(R.drawable.ic_agree_select);
        mBinding.ivOwnBid.setImageResource(R.drawable.ic_agree_normal);
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    //选中的开放城市
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCityChoiceEvent(CityChoiceEvent event) {
        area = event.itemData.areaCode;
        mBinding.tvAddress.setText(event.itemData.abbreviation);

        SPManager.HomeData.saveSelectLocationData(event.itemData);

        resetData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWorkplaceEvent(WorkplaceEvent event) {
        boolean defaultCity = getDefaultCity(event.bean.city, 2);

        OrderParametersBean.AddressData data = new OrderParametersBean.AddressData();
        data.address = event.bean.detailedAddress;
        data.longitude = String.valueOf(event.bean.longitude);
        data.latitude = String.valueOf(event.bean.latitude);
        data.contactPerson = event.bean.name;
        data.contactPhone = AEACCoder.encrypt(event.bean.phone);
        data.city = event.bean.city;

        String contacts;
        if (TextUtils.isEmpty(event.bean.name) && TextUtils.isEmpty(event.bean.phone)) {
            contacts = "未填写联系人";
        } else {
            contacts = event.bean.name + "  " + event.bean.phone;
        }

        switch (event.type) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
                data.addressType = listPlace.get(event.type).isState;

                HomePlaceBean placeBean = new HomePlaceBean();
                placeBean.content = event.bean.detailedAddress;

                placeBean.contacts = contacts;
                placeBean.isState = listPlace.get(event.type).isState;
                placeBean.isHaveData = true;
                placeBean.data = data;
                listPlace.set(event.type, placeBean);
                adapterPlace.refresh();
                break;
            case 999:
                if (defaultCity) {
                    mBinding.tvSingleWorkingField.setText(event.bean.detailedAddress);
                    mBinding.tvSingleWorkingFieldContacts.setText(contacts);
                    mBinding.tvSingleWorkingFieldContacts.setVisibility(View.VISIBLE);
                    isCityPicker = true;
                    singleAddressData.clear();
                    data.addressType = 0;
                    singleAddressData.add(data);
                } else {
                    ToastUtils.showShort("该城市尚未开通");
                }

                break;
            case 888:
                if (defaultCity) {
                    mBinding.tvAddressStart.setText(event.bean.detailedAddress);
                    mBinding.tvAddressStartContacts.setText(contacts);
                    mBinding.tvAddressStartContacts.setVisibility(View.VISIBLE);

                    if (startDischarge) {
                        multipleAddressOne.remove(0);
                    }
                    startDischarge = true;
                    data.addressType = 0;
                    multipleAddressOne.add(0, data);

                } else {
                    ToastUtils.showShort("该城市尚未开通");
                }
                break;
            case 777:
                mBinding.tvAddressEnd.setText(event.bean.detailedAddress);
                mBinding.tvAddressEndContacts.setText(contacts);
                mBinding.tvAddressEndContacts.setVisibility(View.VISIBLE);
                data.addressType = 1;
                if (placeDischarge) {
                    if (startDischarge) {
                        multipleAddressOne.remove(1);
                        multipleAddressOne.add(1, data);
                    } else {
                        multipleAddressOne.remove(0);
                        multipleAddressOne.add(0, data);
                    }
                } else {
                    if (startDischarge) {
                        multipleAddressOne.add(1, data);
                    } else {
                        multipleAddressOne.add(data);
                    }
                }
                placeDischarge = true;


                break;
            default:
        }
    }

    //干活地
    @Override
    public void onWorkingField(int type) {
        if (TextUtils.isEmpty(area)) {
            ToastUtils.showShort("请选择开放城市");
            return;
        }

        IntentManager.toWorkingFieldActivity(mActivity, type, typeModel);
    }


    //干活的地址选择
    @Override
    public void onCommonAddress(int type) {
        if (TextUtils.isEmpty(area)) {
            ToastUtils.showShort("请选择开放城市");
            return;
        }

        IntentManager.toCommonAddressActivity(mActivity, type);
    }

    //增加吊货地
    @Override
    public void onAddCargoPlace() {
        if (listPlace.size() >= 7) {
            ToastUtils.showShort("吊货地不得超过9个");
            return;
        }
        HomePlaceBean placeBean = new HomePlaceBean();
        placeBean.isState = 0;
        placeBean.isHaveData = false;
        placeBean.content = "吊货地";
        placeBean.contacts = "";
        listPlace.add(placeBean);
        adapterPlace.refresh();
    }

    //增加卸货地
    @Override
    public void onAddDischargePlace() {
        if (listPlace.size() >= 7) {
            ToastUtils.showShort("卸货地不得超过9个");
            return;
        }
        HomePlaceBean placeBean = new HomePlaceBean();
        placeBean.isState = 1;
        placeBean.isHaveData = false;
        placeBean.content = "卸货地";
        placeBean.contacts = "";
        listPlace.add(placeBean);
        adapterPlace.refresh();
    }

    //算账方式
    @Override
    public void onSettleAccounts() {
        if (TextUtils.isEmpty(area)) {
            ToastUtils.showShort("请选择开放城市");
            return;
        }

        if (carModelBean == null)
            return;

        accountingMethodPop = new AccountingMethodPop(mActivity, carModelBean.get(mBinding.tabLayout.getTabLayout().getSelectedTabPosition()).model, area);
        accountingMethodPop.setAccountingMethodListener(itemData -> {

            settleAccountsId = itemData.id;
            settleAccountsContent = itemData.content;
            mBinding.tvSettleAccounts.setText(itemData.content);
            isSettleAccounts = true;
            if (!TextUtils.isEmpty(area)) {
                getMarketPriceData();
            }

        });
        accountingMethodPop.showPopupWindow(mBinding.tvAllMachinery);
    }

    //进行中的订单
    @Override
    public void onOrderNotCompleted() {
        if (orderNotCompletedDialogFragment == null)
            orderNotCompletedDialogFragment = new OrderNotCompletedDialogFragment();
        orderNotCompletedDialogFragment.show(mActivity.getSupportFragmentManager());
    }


    public void confirmOrder(String time) {
        OrderParametersBean orderParameters = new OrderParametersBean();
        orderParameters.hour = speechInfoBean.hour;
        orderParameters.minute = speechInfoBean.minute;
        orderParameters.area = area;

        orderParameters.model = carModelBean.get(mBinding.tabLayout.getTabLayout().getSelectedTabPosition()).model;
        orderParameters.workTime = settleAccountsId;
        orderParameters.workContent = settleAccountsContent;
        String amount = "";
        String favorablePrice = "";
        if (priceType == 0) {
            amount = marketPriceBean.price;
            favorablePrice = marketPriceBean.favorablePrice;
        } else if (priceType == 1) {
            amount = mBinding.tvOwnBidPrice.getText().toString().trim();
            if (TextUtils.isEmpty(amount)) {
                ToastUtils.showShort("请输入我的出价");
                return;
            }
        }
        orderParameters.amount = amount;
        orderParameters.favorablePrice = favorablePrice;
        orderParameters.priceType = priceType;

        if (isSingleAndMultiple) {
            multipleAddressData.clear();
            multipleAddressData.addAll(multipleAddressOne);
            multipleAddressTwo.clear();
            for (int i = 0; i < listPlace.size(); i++) {
                if (listPlace.get(i).isHaveData) {
                    multipleAddressTwo.add(listPlace.get(i).data);
                }
            }
            multipleAddressData.addAll(1, multipleAddressTwo);

            addressDataBean.clear();
            addressDataBean.addAll(multipleAddressData);

        } else {
            addressDataBean.clear();
            addressDataBean.addAll(singleAddressData);
        }

        orderParameters.addressData = addressDataBean;

        //确认单子
        IntentManager.toConfirmOrderActivity(mActivity, orderParameters, carModelBean.get(mBinding.tabLayout.getTabLayout().getSelectedTabPosition()), time, marketPriceBean);
    }

    //立即用车
    @Override
    public void onImmediatelyCar() {
        if (TextUtils.isEmpty(area)) {
            ToastUtils.showShort("请选择开放城市");
            return;
        }

        if (isSingleAndMultiple) {
            if (!startDischarge) {
                ToastUtils.showShort("请选择吊货地址");
                return;
            }

            if (!placeDischarge) {
                ToastUtils.showShort("请选择卸货地址");
                return;
            }

        } else {
            if (!isCityPicker) {
                ToastUtils.showShort("请选择地址");
                return;
            }
        }

        if (!isSettleAccounts) {
            ToastUtils.showShort("请选择算账方式");
            return;
        }
        confirmOrder("");
    }

    //选择市场价格
    @Override
    public void onMarketPrice() {
        priceType = 0;
        mBinding.ivMarketPrice.setImageResource(R.drawable.ic_agree_select);
        mBinding.ivOwnBid.setImageResource(R.drawable.ic_agree_normal);
    }

    //预约用车
    @Override
    public void onReservedCar() {

        if (TextUtils.isEmpty(area)) {
            ToastUtils.showShort("请选择开放城市");
            return;
        }

        if (isSingleAndMultiple) {
            if (!startDischarge) {
                ToastUtils.showShort("请选择吊货地址");
                return;
            }

            if (!placeDischarge) {
                ToastUtils.showShort("请选择卸货地址");
                return;
            }

        } else {
            if (!isCityPicker) {
                ToastUtils.showShort("请选择地址");
                return;
            }
        }

        if (!isSettleAccounts) {
            ToastUtils.showShort("请选择算账方式");
            return;
        }

        int hour = Integer.parseInt(speechInfoBean.hour);
        int minute = Integer.parseInt(speechInfoBean.minute);
        ReservedCarTimeBean timeBean = new ReservedCarTimeBean(hour, minute, 1);

        //返回的分别是三个级别的选中位置
        //标题
        //确定和取消文字大小
        //标题文字大小
        //标题文字颜色
        //滚轮文字大小
        pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String time = timeBean.getOptions1Items().get(options1) + "  "
                        + timeBean.getOptions2Items().get(options1).get(option2)
                        + timeBean.getOptions3Items().get(options1).get(option2).get(options3);

                confirmOrder(time);
                pvOptions.dismiss();
            }
        }).setLayoutRes(R.layout.pickerview_custom_condition, (CustomListener) v -> {
            //自定义布局中的控件初始化及事件处理
            final TextView tvDetermine = (TextView) v.findViewById(R.id.tv_determine);
            ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
            tvDetermine.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pvOptions.returnData();
                }
            });
            ivCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pvOptions.dismiss();
                }
            });
        })
                .setLineSpacingMultiplier(3f)//行间距
                .setItemVisibleCount(5)
                .setContentTextSize(20)
                .setTextColorCenter(Color.BLACK).build();

        pvOptions.setPicker(timeBean.getOptions1Items(), timeBean.getOptions2Items(), timeBean.getOptions3Items());//添加数据源
        pvOptions.setSelectOptions(0, 0, 0);
        pvOptions.show();
    }

    //算算账
    @Override
    public void onCalculateAccounts() {
        IntentManager.toCalculateAccountsActivity(mActivity);
    }

    //选择自己出价
    @Override
    public void onChooseOwnBid() {
        priceType = 1;
        mBinding.ivOwnBid.setImageResource(R.drawable.ic_agree_select);
        mBinding.ivMarketPrice.setImageResource(R.drawable.ic_agree_normal);
    }

    //自己出价
    @Override
    public void onOwnBid() {
        ownBidPop = new OwnBidPop(mActivity, marketPriceBean);
        ownBidPop.setOwnBidListener(itemData -> {
            mBinding.llOwnBid.setVisibility(View.VISIBLE);
            mBinding.tvWnBid.setVisibility(View.GONE);
            mBinding.tvOwnBidPrice.setText(itemData);
        });
        ownBidPop.showPopupWindow(mBinding.tvAllMachinery);
    }

    //删除地点
    @Override
    public void onDeletePlace(int position) {
        listPlace.remove(position);
        adapterPlace.refresh();
    }

    //点击机械
    @Override
    public void onClickMechanics(int position, HomeMechanicsBean itemData) {
        if (itemData.isClick)
            return;

        for (int i = 0; i < listMechanics.size(); i++) {
            listMechanics.get(i).isClick = false;
        }
        listMechanics.get(position).isClick = true;
        adapterMechanics.refresh();

        mBinding.tabLayout.getTabLayout().removeAllTabs();
        setLocationType(itemData.multipleAddresses);
        getCarModelData(itemData.type);
    }

    @Override
    public void returnHomeMechanicsBean(List<HomeMechanicsBean> homeMechanicsBean) {
        if (homeMechanicsBean != null && homeMechanicsBean.size() != 0) {
            homeMechanicsBean.get(0).isClick = true;
            listMechanics.addAll(homeMechanicsBean);
            adapterMechanics.refresh();

            setLocationType(homeMechanicsBean.get(0).multipleAddresses);
            getCarModelData(homeMechanicsBean.get(0).type);
        }

    }

    @Override
    public void returnHomeCarModelBean(List<HomeCarModelBean> data) {
        carModelBean = data;
        List<String> titleList = new ArrayList<>();
        List<Fragment> fragmentList = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            titleList.add(data.get(i).describe);
            HomeVehicleTypeFragment listFragment = FragmentManager.getHomeVehicleTypeFragment(i, data.get(i).remark, data.get(i).model, true);
            fragmentList.add(listFragment);
        }
        mBinding.tabLayout.setCustomViewTabLayoutView(getChildFragmentManager(), titleList, fragmentList, true);
    }

    @Override
    public void returnSpeechInfoBean(SpeechInfoBean speechInfoBean) {
        this.speechInfoBean = speechInfoBean;
        mBinding.tvTitle.setTextList(speechInfoBean.news);

        if (speechInfoBean.news != null && speechInfoBean.news.size() != 0)
            mBinding.tvTip.setText(speechInfoBean.news.get(0));
    }

    //市场价格
    @Override
    public void returnMarketPriceData(MarketPriceBean marketPriceBean) {
        if (TextUtils.isEmpty(marketPriceBean.price)) {
//            ToastUtils.showShort("请重新选择开放城市");
            return;
        }
        this.marketPriceBean = marketPriceBean;
        mBinding.llBudget.setVisibility(View.VISIBLE);
        mBinding.llBottom.setBackgroundResource(R.drawable.shape_while_4dp);
        mBinding.tvMarketPrice.setText(marketPriceBean.price);

        if (TextUtils.isEmpty(marketPriceBean.favorablePrice)) {
            mBinding.tvFavorablePrice.setVisibility(View.INVISIBLE);
        } else {
            mBinding.tvFavorablePrice.setVisibility(View.VISIBLE);
            mBinding.tvFavorablePrice.setText(marketPriceBean.favorablePrice);
        }
    }

    //返回的位置信息
    @Override
    public void returnAreaInfoBean(List<CityChoiceBean> cityChoiceBean) {
       /* this.cityChoiceBean = cityChoiceBean;

        if (addressData != null && !TextUtils.isEmpty(addressData.locality)) {
            boolean defaultCity = getDefaultCity(addressData.locality, 1);
            if (!defaultCity) {
                area = cityChoiceBean.get(0).areaCode;
                mBinding.tvAddress.setText(cityChoiceBean.get(0).abbreviation);
            }
        }*/

    }

    //返回的位置信息
    @Override
    public void returnOpenCityData(OpenCityBean openCityBean) {
        this.openCityBean = openCityBean;
        if (selectLocationData != null && !TextUtils.isEmpty(selectLocationData.abbreviation)) {

        }else {
            if (addressData != null && !TextUtils.isEmpty(addressData.locality)) {
                boolean defaultCity = getDefaultCity(addressData.locality, 1);
            /*if (!defaultCity) {
                area = cityChoiceBean.get(0).areaCode;
                mBinding.tvAddress.setText(cityChoiceBean.get(0).abbreviation);
            }*/
            }
        }
    }

    public boolean getDefaultCity(String locality, int type) {
        String currentAddress = locality.replace("市", "");

        for (int i = 0; i < openCityBean.provinceList.size(); i++) {
            for (int j = 0; j < openCityBean.provinceList.get(i).cityList.size(); j++) {
                if (currentAddress.equals(openCityBean.provinceList.get(i).cityList.get(j).name)) {

                    CityChoiceBean bean=new CityChoiceBean();
                    bean.abbreviation=openCityBean.provinceList.get(i).cityList.get(j).name;
                    bean.areaCode=openCityBean.provinceList.get(i).cityList.get(j).areaCode;
                    if (type == 1) {
                        //area = openCityBean.provinceList.get(i).cityList.get(j).areaCode;
                        bean.longitude=addressData.longitude+"";
                        bean.latitude=addressData.latitude+"";
                    }else {
                        bean.longitude=openCityBean.provinceList.get(i).cityList.get(j).longitude;
                        bean.latitude=openCityBean.provinceList.get(i).cityList.get(j).latitude;
                    }
                    mBinding.tvAddress.setText(openCityBean.provinceList.get(i).cityList.get(j).name);
                    area=bean.areaCode;
                    SPManager.HomeData.saveSelectLocationData(bean);
                    return true;
                }
            }
        }
        return false;
    }

    public void setLocationType(Boolean type) {
        isSingleAndMultiple = type;
        mBinding.llSingleWorkingField.setVisibility(type ? View.GONE : View.VISIBLE);
        mBinding.llMultipleWorkingField.setVisibility(type ? View.VISIBLE : View.GONE);
    }

    public void getMarketPriceData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));
        map.put("model", carModelBean.get(mBinding.tabLayout.getTabLayout().getSelectedTabPosition()).model);
        map.put("id", settleAccountsId);
        map.put("area", area);
        mViewModel.getMarketPriceData(map);
    }

    @Override
    public void onResume() {
        super.onResume();
        mBinding.tvTitle.startAutoScroll();
    }

    @Override
    public void onPause() {
        super.onPause();
        mBinding.tvTitle.stopAutoScroll();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGrabOrderLoginStateEvent(GrabOrderLoginStateEvent event) {
        LoadingFragmentManager.getInstance().dismissLoadingDialog();
        if (event.state) {
            mBinding.ivState.setImageResource(R.drawable.ic_line_on);
            mBinding.tvStateText.setText("在线");
            mBinding.tvReconnect.setVisibility(View.GONE);

        } else {
            mBinding.ivState.setImageResource(R.drawable.ic_line_off);
            mBinding.tvStateText.setText("离线");
            mBinding.tvReconnect.setVisibility(View.VISIBLE);
        }
        mBinding.llState.setVisibility(View.VISIBLE);
    }
}
